package com.casic.worklog.filter;

import  com.casic.worklog.model.Employee;
import com.casic.worklog.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
@WebFilter(filterName = "LoginFilter", urlPatterns = "/", dispatcherTypes = {})
public class loginFilter implements Filter {
    @Autowired
    EmployeeService employeeService;
    public static final String NO_INTERCEPTOR_PATH = ".*/((.ico)|(css)|(js)|(images)|(login)|(loginCheck.ht)|(login.do)|(anon)).*";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req =(HttpServletRequest) request;
        HttpServletResponse res =(HttpServletResponse) response;
        String path = req.getServletPath();
        System.out.println("path==" + path);
        if (path.matches(NO_INTERCEPTOR_PATH)) {
            // System.out.println("passUrl==" + path);
            // 不需要的拦截直接过
            chain.doFilter(request, response);
        } else {
            // 这写你拦截需要干的事儿，比如取缓存，SESSION，权限判断等
            Employee userInfoVo = (Employee)req.getSession().getAttribute("loginer");
            if (userInfoVo==null) {
                res.sendRedirect("/workLog/login");//跳转登录页面
                return;
            }else {
                if("/".equals(path)) {//登录之后访问根目录要放行跳转mainMenu.jsp
                    res.sendRedirect("/workLog/login");//跳转登录成功页面
                } else {
                    // System.out.println("passUrlHasSession==" + path);
                    chain.doFilter(request, response);
                }
            }
//          res.sendRedirect("www.baidu.com");

        }
    }

    @Override
    public void destroy() {
    }

}
